package cn.imjzm.runcarserve.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class Redis {

    @Autowired
    private StringRedisTemplate redisTemplate;


    // 存储任意对象，自动转 JSON
    public <T> void setValue(String key, T value) {
        setValue(key,value,-1);
    }

    // 存储任意对象，自动转 JSON
    public <T> void setValue(String key, T value, long timeoutSeconds) {
        String json = JSONObject.toJSONString(value);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        if (timeoutSeconds == -1){
            operations.set(key, json);
        }else{
            operations.set(key, json, timeoutSeconds, TimeUnit.SECONDS);
        }


    }
    class user {
        private String name;
        private Integer age;
    }

    user user = new user();


    // 读取 JSON 自动转对象
    public <T> T getValue(String key, Class<T> clazz) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String json = operations.get(key);
        if (json == null) return null;
        return JSONObject.parseObject(json, clazz);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
